<template>
	<view class="page-body">
		<!-- 表格搜索组件开始 -->
		<vk-data-table-query v-model="queryForm1.formData" :columns="queryForm1.columns" @search="search">
		</vk-data-table-query>
		<!-- 表格搜索组件结束 -->



		<view v-if="vk.vuex.get('$user.userInfo.username')=='admin'">

			<vk-data-table ref="table1" :action="table1.action" :columns="table1.columns" :query-form-param="queryForm1"
				:right-btns="['detail_auto',]"  :selection="true"
				:row-no="true" :pagination="true"  @current-change="currentChange"
				@selection-change="selectionChange">
			</vk-data-table>
			<!-- 表格组件结束 -->
		</view>

		<view v-else>
			<!-- 表格组件开始 -->
			<vk-data-table ref="table1" :action="table1.action" :columns="table1.columns" :query-form-param="queryForm1"
				:right-btns="['more']" :right-btns-more="table1.rightBtnsMore" :selection="false" :row-no="true"
				:pagination="true" @current-change="currentChange" @selection-change="selectionChange">
			</vk-data-table>
			<!-- 表格组件结束 -->
		</view>




		<!-- 页面内容结束 -->
	</view>
</template>

<script>
	var that; // 当前页面对象
	var vk = uni.vk; // vk实例
	var originalForms = {}; // 表单初始化数据
	const db = uniCloud.database();
	const OSS = require('ali-oss');
	export default {
		data() {
			// 页面数据变量
			return {
				store: {},
				baseurl: "",
				tips: "请勿关闭浏览器...",
				currentserie: 1,
				currentlink: "", //当前播放视频链接
				temp_series_list: [],
				dialogVisible: false, //控制弹窗是否开启
				// 页面是否请求中或加载中
				loading: false,
				// init请求返回的数据
				data: {

				},
				// 表格相关开始 -----------------------------------------------------------
				table1: {

					// 表格数据请求地址
					action: "admin/pages/files_mzgl/dy_error/kh/getList",
					// 表格字段显示规则
					columns: [{
							"key": "err_msg",
							"title": "报错信息",
							"type": "string",
						},
						{
								"key": "_add_time_str",
								"title": "添加时间",
								"type": "string",
							},







					],
					// 多选框选中的值
					multipleSelection: [],
					// 当前高亮的记录
					selectItem: ""
				},
				// 表格相关结束 -----------------------------------------------------------
				// 表单相关开始 -----------------------------------------------------------
				// 查询表单请求数据
				queryForm1: {
					// 查询表单数据源，可在此设置默认值
					formData: {

					},
					// 查询表单的字段规则 fieldName:指定数据库字段名,不填默认等于key
					columns: [
					]
				},
				form1: {
					// 表单请求数据，此处可以设置默认值
					data: {
						//设置默认值
						album_id: 0, //默认返回的
					},
					// 表单属性
					props: {
						// 表单请求地址
						action: "",
						// 表单字段显示规则
						columns: [{
								"key": "ma_app_id",
								"title": "小程序appid",
								"type": "text"
							},

							{
								key: "album_info",
								title: "短剧信息",
								type: "object",
								columns: [{
										"key": "title",
										"title": "短剧标题",
										"type": "text"
									},
									{
										"key": "seq_num",
										"title": "总集数",
										"type": "number",
										"placeholder": "该剧总集数，填写数字即可"
									},

									{
										"key": "cover_list",
										title: "封面图列表",
										type: "table-select",
										placeholder: "请选择封面",
										tips: "请选择有封面id的图片",
										"action": "admin/system_uni/uni-id-files/files/kh/getList",
										"columns": [{
												key: "open_pic_id",
												title: "封面id",
												type: "text",
												idKey: true,
												nameKey: true

											},
											{
												key: "url",
												title: "封面",
												type: "image",
											},
										],
										multiple: true,
										watch: (res) => {
											if (typeof res.option[0].open_pic_id === "undefined") {
												// 变量的值为 undefined
												vk.alert('该图片没有图片id，请重新选择');
												return
											}
											this.form1.data.album_info.cover_list = vk.pubfn
												.arrayObjectGetArray(res.option, "open_pic_id")
											console.log("watch", res)
											console.log("cover_list:", this.form1.data.album_info.cover_list);
										}
									},
									{
										"key": "year",
										"title": "发行年份",
										"type": "number",
										"placeholder": "该剧发行年份，填写数字即可"
									},
									{
										"key": "album_status",
										"title": "短剧更新状态",
										"type": "select",
										"data": [
											// {
											// 	value: 1,
											// 	label: "未上映"
											// },
											// {
											// 	value: 2,
											// 	label: "更新中"
											// },
											{
												value: 3,
												label: "已完结"
											},
										],
									},
									{
										"key": "recommendation",
										"title": "短剧推荐语",
										"type": "text",
										"placeholder": "12个汉字以内"
									},
									{
										"key": "desp",
										"title": "短剧简介",
										"type": "textarea",
										"placeholder": "200个汉字以内",
										"autosize": {
											minRows: 4,
											maxRows: 10
										},
										"maxlength": 200,
										"showWordLimit": true,
									},

									{
										"key": "tag_list",
										"title": "短剧类目标签",
										"type": "select",
										"filterable": true,
										"clearable": true,
										"data": [{
												value: 1,
												label: "医神"
											},
											{
												value: 2,
												label: "赘婿"
											},
											{
												value: 3,
												label: "鉴宝"
											},
											{
												value: 4,
												label: "战神"
											},
											{
												value: 5,
												label: "娱乐明星"
											},
											{
												value: 6,
												label: "神医"
											},
											{
												value: 7,
												label: "重生"
											},
											{
												value: 8,
												label: "职场"
											},
											{
												value: 9,
												label: "逆袭"
											},
											{
												value: 10,
												label: "复仇"
											},
											{
												value: 11,
												label: "青春"
											},
											{
												value: 12,
												label: "官场"
											},
											{
												value: 13,
												label: "家庭情感"
											},
											{
												value: 14,
												label: "乡村"
											},
											{
												value: 15,
												label: "正能量"
											},
											{
												value: 16,
												label: "成长"
											},
											{
												value: 17,
												label: "伦理"
											},
											{
												value: 18,
												label: "都市情感"
											},
											{
												value: 19,
												label: "社会话题"
											},
											{
												value: 20,
												label: "灵异"
											},
											{
												value: 21,
												label: "悬疑推理"
											},
											{
												value: 22,
												label: "虐恋"
											},
											{
												value: 23,
												label: "甜宠"
											},
											{
												value: 24,
												label: "高干军婚"
											},
											{
												value: 25,
												label: "年代"
											},
											{
												value: 26,
												label: "萌宝"
											},
											{
												value: 27,
												label: "腹黑"
											},
											{
												value: 28,
												label: "总裁"
											},
											{
												value: 29,
												label: "宫斗宅斗"
											},
											{
												value: 30,
												label: "穿越"
											},
											{
												value: 31,
												label: "种田经商"
											},
											{
												value: 33,
												label: "民俗"
											},
											{
												value: 34,
												label: "古装"
											},
											{
												value: 35,
												label: "穿越战争"
											},
											{
												value: 36,
												label: "现代军事"
											},
											{
												value: 37,
												label: "奇幻"
											},
											{
												value: 38,
												label: "科幻"
											},
											{
												value: 39,
												label: "架空玄幻"
											},
											{
												value: 40,
												label: "热血"
											},
											{
												value: 41,
												label: "历史"
											},
											{
												value: 42,
												label: "搞笑"
											},
											{
												value: 43,
												label: "仙侠"
											},
											{
												value: 44,
												label: "武侠"
											},
											{
												value: 45,
												label: "二次元"
											},
											{
												value: 46,
												label: "其他"
											}
										],
										"placeholder": "1-3个。示例:[1]",
										watch: (res) => {

											this.form1.data.album_info.tag_list = vk.pubfn.arrayObjectGetArray(
												res.option, "value")

											console.log("watch", res)
										},
										multiple: true,
									},
									{
										"key": "qualification",
										"title": "资质状态",
										"type": "select",
										"data": [{
												value: 1,
												label: "未报审"
											},
											{
												value: 2,
												label: "报审通过"
											},
											{
												value: 3,
												label: "报审不通过"
											},
											{
												value: 4,
												label: "不建议报审"
											},
										],


									},
								],

							},

							{
								key: "record_info",
								title: "备案信息(包含一种备案号即可)",
								type: "object",
								columns: [{
										key: "license_num",
										title: "许可证号",
										type: "text",
										tips: "未报审时不用填写"
									},
									{
										key: "registration_num",
										title: "登记号",
										type: "text",
										tips: "未报审时不用填写"
									},
									{
										key: "ordinary_record_num",
										title: "普通备案号",
										type: "text",
										tips: "未报审时不用填写"
									},
									{
										key: "key_record_num",
										title: "重点备案号",
										type: "text",
										tips: "未报审时不用填写"
									},
								],


								disabled: (album_info) => {
									console.log("album_info", album_info.album_info.qualification);
									if (album_info.album_info.qualification == 1) {
										this.form1.data.record_info.license_num = ""
										this.form1.data.record_info.registration_num = ""
										this.form1.data.record_info.ordinary_record_num = ""
										this.form1.data.record_info.key_record_num = ""
										return true;
									} else {
										console.log(222);
										return false;
									}
								},
							},


						],
						// 表单验证规则
						rules: {
							ma_app_id: [{
								required: true,
								message: "appid必须填写",
								trigger: ['blur', 'change']
							}],
							album_info: [{
								required: true,
								message: "必填",
								trigger: ['blur', 'change']
							}],
							title: [{
								required: true,
								message: "必填",
								trigger: ['blur', 'change']
							}],
							seq_num: [{
								required: true,
								message: "必填",
								trigger: ['blur', 'change']
							}],
							cover_list: [{
								required: true,
								message: "必填",
								trigger: ['blur', 'change']
							}],
							year: [{
								required: true,
								message: "必填",
								trigger: ['blur', 'change']
							}],
							album_status: [{
								required: true,
								message: "必填",
								trigger: ['blur', 'change']
							}],
							recommendation: [{
								required: true,
								message: "必填",
								trigger: ['blur', 'change']
							}],
							desp: [{
								required: true,
								message: "必填",
								trigger: ['blur', 'change']
							}],
							tag_list: [{
									required: true,
									message: "必填",
									trigger: ['blur', 'change']
								}

							],
							qualification: [{
									required: true,
									message: "必填",
									trigger: ['blur', 'change']
								},

							],
						},
						// add 代表添加 update 代表修改
						formType: "",
						// 是否显示表单的弹窗
						show: false
					}
				},
				// 其他弹窗表单
				formDatas: {},
				// 表单相关结束 -----------------------------------------------------------
			};
		},
		// 监听 - 页面每次【加载时】执行(如：前进)
		onLoad(options = {}) {
			that = this;
			vk = that.vk;
			that.options = options;
			that.init(options);
		},
		// 监听 - 页面【首次渲染完成时】执行。注意如果渲染速度快，会在页面进入动画完成前触发
		async onReady() {
			const alioss = await db.collection('a_config').where({
				name: "alioss"
			}).get();
			// vk.setVuex('$app.ossinfo', ossinfo) //把阿里云oss配置存到本地缓存	

			if (alioss.result.data[0]) {
				let ossinfo = alioss.result.data[0];
				this.store = new OSS({
					// yourRegion填写Bucket所在地域。以华东1（杭州）为例，yourRegion填写为oss-cn-hangzhou。
					region: ossinfo.region,
					// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
					accessKeyId: ossinfo.accessKeyId,
					accessKeySecret: ossinfo.accessKeySecret,
					// 填写Bucket名称。
					bucket: ossinfo.bucket
				});
				this.baseurl = ossinfo.baseurl;
			} else {
				this.store = new OSS({
					// yourRegion填写Bucket所在地域。以华东1（杭州）为例，yourRegion填写为oss-cn-hangzhou。
					region: "test",
					// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
					accessKeyId: "test",
					accessKeySecret: "test",
					// 填写Bucket名称。
					bucket: "test",
				});
				this.baseurl = ""
			}
		},
		// 监听 - 页面每次【显示时】执行(如：前进和返回) (页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面)
		onShow() {
			console.log("oss=", vk.vuex.get('$app.ossinfo.region'));
		},
		// 监听 - 页面每次【隐藏时】执行(如：返回)
		onHide() {},
		// 函数
		methods: {
			async getSecUrl(tempUrl) {
				//如果数据库里没配置相关参数，则原样返回
				if (!this.baseurl) {
					return tempUrl;
				}
				let suffix = tempUrl.substr(-4); //截取后四位,如果后4位不是.mp4，说明已经获取过签名
				console.log("suffix=", suffix);
				if (suffix == ".mp4" || suffix == ".MP4") {
					//避免有些文件是http，因此统一替换成https
					tempUrl = tempUrl.replace('http://', 'https://');
					//清空域名信息，只留文件名信息，例如：anna/1.mp4
					let videoFile = tempUrl.replace(this.baseurl, '');
					//生成带签名的url
					let url = this.store.signatureUrl(videoFile, {
						expires: 3600, //3600秒到期
					});
					return url;
				} else {
					return tempUrl;
				}

			},
			async batchAdd(item) {
				//如果已存在_id,就是编辑，否则就是新增（此处只能是已_id为判定条件）
				if (item._id) {
					vk.callFunction({
						url: 'admin/pages/files_mzgl/dy_tv/kh/update',
						title: '请求中...',
						data: {
							_id: item._id,
							ma_app_id: item.ma_app_id,
							album_id: item.album_id, // 短剧id
							album_info: item.album_info,
							record_info: item.record_info,
							audit_status: item.audit_status, // 审核状态  默认 未送审
							status: item.status, // 创建状态
							// online_status:item.online_status,   // 上线状态
							_add_time: new Date().getTime(),
							_add_time_str: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss")
						},
						success: (data) => {
							this.form1.props.show = false; //关闭编辑窗口
							this.refresh()
						}
					});
					return;
				} else {
					if (!this.form1.data.ma_app_id) {
						vk.alert('小程序appid参数不完整，请检查必填项');
						return;
					}

					if (!this.form1.data.album_info.title) {
						vk.alert('短剧标题参数不完整，请检查必填项');
						return;
					}

					if (!this.form1.data.album_info.seq_num) {
						vk.alert('总集数参数不完整，请检查必填项');
						return;
					}

					if (!this.form1.data.album_info.cover_list) {
						vk.alert('封面图列表参数不完整，请检查必填项');
						return;
					}

					if (!this.form1.data.album_info.year) {
						vk.alert('发行年份参数不完整，请检查必填项');
						return;
					}

					if (!this.form1.data.album_info.album_status) {
						vk.alert('短剧更新状态参数不完整，请检查必填项');
						return;
					}

					if (!this.form1.data.album_info.recommendation) {
						vk.alert('短剧推荐语参数不完整，请检查必填项');
						return;
					}

					if (!this.form1.data.album_info.desp) {
						vk.alert('短剧简介参数不完整，请检查必填项');
						return;
					}

					if (this.form1.data.album_info.tag_list.length == 0 || this.form1.data.album_info.tag_list
						.length >
						3) {
						vk.alert('短剧类目标签参数有误，请检查必填项');
						return;
					}

					if (!this.form1.data.album_info.qualification) {
						vk.alert('资质状态参数不完整，请检查必填项');
						return;
					}



					console.log('ma_app_id', item.ma_app_id);
					console.log('ma_app_id', item.album_info);

					let timenow = new Date().getTime();
					let addtv = await db.collection('dy_tv').add({
						ma_app_id: item.ma_app_id,
						album_id: item.album_id, // 短剧id
						album_info: item.album_info,
						record_info: item.record_info,
						audit_status: 1, // 审核状态  默认 未送审
						status: false, // 创建状态
						online_status: false, // 上线状态
						_add_time: timenow,
						_add_time_str: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss")
					})



					let all_series = item.album_info.seq_num;
					for (var i = 0; i < all_series; i++) {
						uni.showToast({
							title: i + "/" + all_series + "，请勿关闭浏览器...",
							icon: 'loading'
						})
						let seq = i + 1;
						let add = await db.collection('dy_tv_series').add({
							ma_app_id: item.ma_app_id,
							cover_list: [item.album_info.cover_list[0]],
							url: "http://" + item.album_info.title + "第" + seq +
								"集.mp4", // 必须有扩展名 才能同步到控制台 （大概两分钟控制台会显示）
							title: item.album_info.title + " - 第" + seq + "集", //  此内容不会覆盖抖音云原本的内容
							format: "mp4",
							use_dy_cloud: true,
							dy_cloud_id: "", //vid默认为0,需用户自填
							open_video_id: "", //pid默认为0,抖音开放平台视频id,需用户填写vid上传获取
							episode_id: "", //剧集id
							seq: seq,
							status: false, // 上传状态
							tv_id: addtv.result.id,
							_add_time: timenow,
							_add_time_str: vk.pubfn.timeFormat(new Date(), "yyyy-MM-dd hh:mm:ss")
						})
					}
					this.form1.props.show = false; //关闭编辑窗口
					vk.alert('恭喜！添加完成');
					this.refresh()
				}
			},
			copylink() {
				let that = this;
				uni.downloadFile({
					url: this.currentlink,
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {}
				});
				uni.setClipboardData({
					data: this.currentlink,
					success() {
						// vk.toast('复制成功', 'none');
						that.$message({
							message: '视频链接复制成功：' + that.currentlink,
							type: 'success'
						});
					}
				})
			},
			//点按钮换集
			async cut_serie(item) {

				this.currentlink = item.video_src
				this.currentserie = item.series

			},
			//弹窗关闭前做一下判断或操作
			handleClose() {
				this.dialogVisible = false;
			},
			// 页面数据初始化函数
			init(options) {
				originalForms["form1"] = vk.pubfn.copyObject(that.form1);
			},
			// 页面跳转
			pageTo(path) {
				vk.navigateTo(path);
			},
			// 表单重置
			resetForm() {
				vk.pubfn.resetForm(originalForms, that);
			},
			// 搜索
			search() {
				that.$refs.table1.search();
			},
			// 刷新
			refresh() {
				that.$refs.table1.refresh();
			},
			// 获取当前选中的行的数据
			getCurrentRow() {
				return that.$refs.table1.getCurrentRow();
			},
			// 监听 - 行的选中高亮事件
			currentChange(val) {
				that.table1.selectItem = val;
			},
			// 当选择项发生变化时会触发该事件
			selectionChange(list) {
				that.table1.multipleSelection = list;
			},
			// 显示添加页面
			addBtn() {
				that.resetForm();
				that.form1.props.action = 'admin/pages/kh/dsjzxgl/dsj/add';
				that.form1.props.formType = 'add';
				that.form1.props.title = '添加';
				that.form1.props.show = true;
			},
			// 显示修改页面
			updateBtn({
				item
			}) {
				that.form1.props.action = 'admin/pages/kh/dsjzxgl/dsj/update';
				that.form1.props.formType = 'update';
				that.form1.props.title = '编辑';
				that.form1.props.show = true;
				that.form1.data = item;
			},
			// 删除按钮
			deleteBtn({
				item,
				deleteFn
			}) {
				if (item.status) {
					vk.alert('创建成功的，别删');
					return false
				} else {
					console.log("能删");
					deleteFn({
						action: "admin/pages/files_mzgl/dy_tv/kh/delete",
						data: {
							_id: item._id
						},
					});
				}

			},
			// 监听 - 批量操作的按钮点击事件
			batchBtn(index) {
				switch (index) {
					case 1:
						vk.callFunction({
							url: 'admin/pages/kh/dsjzxgl/dsj/batchup',
							title: '请求中...',
							data: {
								lists: this.table1.multipleSelection
							},
							success: (data) => {
								console.log("执行完成");
								this.refresh()
							}
						});
						break;
					case 2:
						vk.callFunction({
							url: 'admin/pages/kh/dsjzxgl/dsj/batchdown',
							title: '请求中...',
							data: {
								lists: this.table1.multipleSelection
							},
							success: (data) => {
								console.log("执行完成");
								this.refresh()
							}
						});
						break;
					default:
						break;
				}
			}
		},
		// 监听属性
		watch: {

		},
		// 过滤器
		filters: {

		},
		// 计算属性
		computed: {

		}
	};
</script>
<style lang="scss" scoped>
	.page-body {}

	// 滚动条样式
	/deep/ ::-webkit-scrollbar {
		/*滚动条整体样式*/
		width: 4px !important;
		height: 1px !important;
		overflow: auto !important;
		background: #ccc !important;
		-webkit-appearance: auto !important;
		display: block;
	}

	/deep/ ::-webkit-scrollbar-thumb {
		/*滚动条里面小方块*/
		border-radius: 10px !important;
		box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2) !important;
		background: #7b7979 !important;
	}

	/deep/ ::-webkit-scrollbar-track {
		/*滚动条里面轨道*/
		// box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2) !important;
		// border-radius: 10px !important;
		background: #FFFFFF !important;
	}
</style>